package io.zhiller.ollamaclient.api.git

import io.zhiller.ollamaclient.api.HttpClient
import io.zhiller.ollamaclient.api.HttpResponse
import io.zhiller.ollamaclient.api.HttpStatus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.URLEncoder

class GitService {
  companion object {
    const val GIT_TOKEN = "ccb69867f6e2479a5bad18912b98ea5b"
    const val GIT_OWNER = "zhillerdev_compose_samples"
    const val GIT_REPO = "ollama-client"
  }
  
  fun getApiUrl(
    onSuccess: (HttpResponse<GitGetFileResponse>) -> Unit,
    onError: (Throwable) -> Unit,
  ) {
    val textPath = URLEncoder.encode("assets/api.txt", "UTF-8")
    val parameters = buildString { append("?access_token=$GIT_TOKEN") }
    
    val url = "https://gitee.com/api/v5/repos/$GIT_OWNER/$GIT_REPO/contents/$textPath$parameters"
    
    CoroutineScope(Dispatchers.IO).launch {
      try {
        val response = HttpClient.getJsonFromUrl<GitGetFileResponse>(url)
        withContext(Dispatchers.Main) {
          when (response.status) {
            HttpStatus.SUCCESS -> onSuccess(response)
            HttpStatus.FAILURE -> onError(Exception("请求失败"))
            HttpStatus.ERROR -> onError(Exception("请求错误"))
          }
        }
      } catch (e: Exception) {
        withContext(Dispatchers.Main) {
          onError(e)
        }
      }
    }
  }
  
}